import { Controller } from 'egg';
import tenpay from 'tenpay';
import { ORDER_STATUS_KEYS } from '../../common/constants';
import { getOrderId, getCurrentStimp } from '../../utils/index';


export const compCatOptions = [
  { id: 1, label: '独奏组', price: 480 },
  { id: 2, label: '专业独奏组', price: 580 },
  { id: 3, label: '组合组', price: 380 },
  { id: 4, label: '专业组合组', price: 380 },
];
export default class ActivityController extends Controller {

  constructor(ctx) {
    super(ctx);
    // this.service = ctx.service.wx.order;
  }

  async infoList() {
    this.ctx.success({
      data: {
        list: '123',
      },
    });
  }

  async infoDetail() {
    const { id } = this.ctx.query;

    const activityInfo = await this.service.activity.info.findById(parseInt(id ?? 1));
    this.ctx.success({
      data: {
        activityInfo,
      },
    });
  }

  async createApply() {

    // const { body } = this.ctx.validateReq('xxm.activity.apply.create');
    const body = this.ctx.request.body;
    const { openid: user_id } = this.ctx.state.user;
    const shop_id = this.ctx._shop.id;
    const order_id = getOrderId();

    const insertApplyInfo = {
      ...body,
      userId: user_id,
      activityId: parseInt(body.activityId),
      order_id,
      shop_id,
    };
    await this.service.activity.apply.create(insertApplyInfo);


    // const { user_id, people_number = , table_number, order_type, note } = body;
    // const { list: carList } = await this.ctx.service.wx.cart.list({ user_id });

    // if (carList.length === 0) {
    //   this.ctx.failure({
    //     msg: '请重新选择商品'
    //   });
    //   return;
    // }

    const stemp = getCurrentStimp();

    // const orderGoods = carList.map((it: any) => {
    //   const {
    //     goods_id, number, Good: {
    //       price, main_pic, name, market_price, brief
    //     }
    //   } = it;
    //   return {
    //     order_id,
    //     goods_id,
    //     price,
    //     main_pic,
    //     number,
    //     brief,
    //     market_price,
    //     goods_name: name,
    //     create_at: stemp,
    //     update_at: stemp
    //   };
    // });
    // const all_price = carList.filter(t => t.Good).reduce((p, n) => {
    //   return p + n.Good.price * n.number
    // }, 0);


    const groupRegistersArr = JSON.parse(insertApplyInfo.groupRegisters);
    if (!Array.isArray(groupRegistersArr) || groupRegistersArr.length < 2) {
      return;
    }
    if (!insertApplyInfo.compCat) {
      return;
    }
    const cat = parseInt(insertApplyInfo.compCat);
    const itemPrice = compCatOptions.find(v => v.id === cat)?.price;
    if (!itemPrice) {
      return;
    }
    let enrollPrice = 1;
    if ([ 3, 4 ].includes(cat)) {
      enrollPrice = itemPrice * groupRegistersArr.length;
    } else {
      enrollPrice = itemPrice;
    }
    enrollPrice = enrollPrice * 100;
    // 其他价格
    // let other_price = 0;
    const table_cost = 0;
    const pack_cost = 0;
    const all_price = enrollPrice;
    const people_number = 0;
    const table_number = 0;
    const order_type = '';
    const note = '';

    // const shop = await this.ctx.model.Shop.findOne({
    //   where: { uuid: this.ctx.headers.shopuuid }
    // });
    // const { tableware, pack, type } = shop;

    // const [CATERING, OTHER] = SHOP_TYPE;
    // const [INSTORE, TAKEOUT, PICKUP] = ORDER_TYPE;

    // // 餐饮
    // if (type === CATERING) {
    //   // 堂食(餐具费)
    //   if (order_type === INSTORE) {
    //     table_cost = tableware * people_number;
    //     other_price += table_cost;
    //   }
    //   // 外卖(打包费)
    //   if (order_type === TAKEOUT || order_type === PICKUP) {
    //     pack_cost = pack * sum(orderGoods.map(it => it.number || 1));
    //     other_price += pack_cost;
    //   }
    // }

    const order = {
      note,
      order_id,
      user_id,
      create_time: stemp,
      all_price,
      people_number,
      table_number,
      order_type, // 默认堂食订单
      table_cost,
      pack_cost,
      status: ORDER_STATUS_KEYS.WAIT_PAY,
      create_at: stemp,
      update_at: stemp,
    };
    // 餐饮 -> 取餐号
    // if (type === CATERING) {
    //   const currDay = new Date().toLocaleDateString().split('/').join('');
    //   const keyDay = `meal_${currDay}`;
    //   const currNumber = this.ctx.service.set.cache.get(keyDay);
    //   let meal_number = 1;
    //   if (currNumber) {
    //     meal_number = currNumber + 1;
    //   }
    //   this.ctx.service.cache.set(keyDay, meal_number, 3600 * 48 * 1000) //缓存2天
    //   Object.assign(order, { meal_number });
    // }

    // // 商铺类型 (餐饮 + 外卖订单  ||  其他 + 外送) => 处理地址信息
    // if (((type === CATERING && order_type === TAKEOUT) || type === OTHER) && address_id) {
    //   const address = await this.ctx.service.wx.address.model.findOne({
    //     where: { id: address_id }
    //   });

    //   const addressInfo = Object.assign(
    //     pick(
    //       address,
    //       ['name', 'mobile', 'address_name', 'address_detail', 'address_description']
    //     ),
    //     {
    //       order_id,
    //       create_at: stemp,
    //       update_at: stemp,
    //     });
    //   await this.ctx.sassmodel.OrderAddress.create(addressInfo);
    // }

    // await this.ctx.sassmodel.OrderGoods.bulkCreate(orderGoods);

    // 插入订单表
    await this.ctx.service.wx.order.create(order);

    // 清空购物车
    // await this.ctx.service.wx.cart.clear(user_id);

    // 微信统一下单
    const { payInfo: { domain, notify_url } } = this.ctx.app.config;
    // const partner_key = fs.readFileSync(path.join(__dirname, '../../common/1643148695_20230427_cert/apiclient_cert.p12'));
    // console.log(pKey, 'pKey')
    const { partner_key, mchid, appid } = await this.ctx.service.shop.merchant.model.findOne({
      where: { id: this.ctx._shop.id },
    });
    const payConfig = {
      appid,
      mchid,
      partnerKey: partner_key, // partnerKey
    };
    const PAYAPI = new tenpay(payConfig);
    const payParams = {
      out_trade_no: order_id,
      body: '支付报名费',
      total_fee: all_price,
      openid: user_id,
      notify_url: domain + notify_url,
    };
    const result = await PAYAPI.unifiedOrder(payParams);

    this.ctx.success({
      data: result,
    });

    // this.ctx.success({
    //   data: {
    //     applyInfo,
    //   },
    // });
  }


  async applyList() {

  }

  async applyDetail() {

  }

  async myApply() {
    // const { openid: user_id } = this.ctx.state.user;
    // const shop_id = this.ctx._shop.id;
    // const applyList = await this.ctx.model.ActivityApply.findAll({ where: { userId: user_id, shop_id, is_delete: 0 },
    //   order: [[ 'id', 'DESC' ]],
    //   include: [
    //     {
    //       model: this.ctx.model.Activity,
    //       as: 'activity',
    //     },
    //     {
    //       model: this.ctx.model.Order,
    //       as: 'order',
    //     },
    //   ] });

    // this.ctx.success({
    //   data: {
    //     applyList,
    //   },
    // });
  }

}
